package com.ai.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ai.common.analyze.CipherUtils;
import com.ai.common.controller.BaseController;
import com.ai.mmd.reviewed.dto.DlxxDTO;
import com.ai.mmd.reviewed.dto.QyshclDTO;
import com.ai.mmd.reviewed.dto.QyzhDTO;
import com.ai.mmd.reviewed.dto.YhxxDTO;
import com.ai.service.reviewed.model.DlxxModel;
import com.ai.service.reviewed.model.QyshclModel;
import com.ai.service.reviewed.model.QyzhModel;
import com.ai.service.reviewed.model.YhxxModel;
import com.ai.service.reviewed.service.IDlxxService;
import com.ai.service.reviewed.service.IQyshclService;
import com.ai.service.reviewed.service.IQyzhService;
import com.ai.service.reviewed.service.IYhxxService;

/**
 * 
 * Class Name : IndexController<br>
 * 
 * Description : 首页Controller类<br>
 * 
 * @see
 *
 */

@Controller("com.ai.controller.MemberController")
public class MemberController extends BaseController {

	
	@Resource(name = "iyhxxService")
	private IYhxxService iyhxxService;
	@Resource(name = "idlxxService")
	private IDlxxService idlxxService;
	@Resource(name = "iqyshclService")
	private IQyshclService iqyshclService;
	@Resource(name = "iqyzhService")
	private IQyzhService iqyzhService;
	
	@Value("${mainDomain}")
	private String mainDomain;

	/**
	 * Description ：会员信息管理
	 * @throws Exception 
	 */
	@RequestMapping("member/memberxxgl")
	public ModelAndView memberxxgl() throws Exception {
				
		ModelAndView mv = new ModelAndView("/front/frontgoods/member/hyxxgl");
		YhxxDTO yhxxDTO = new YhxxDTO();
		if (request.getSession().getAttribute("yhid")!=null) {
			yhxxDTO.setYhid(request.getSession().getAttribute("yhid").toString());
		}		
		YhxxModel yhxx = iyhxxService.getOne(yhxxDTO);
		mv.addObject("yhxx", yhxx);
		if (yhxx!=null) {
			mv.addObject("isnew", "2");
			//查出列表
			List<QyshclModel> list = iqyshclService.getList(new QyshclDTO(yhxx.getYhid()));
			for (QyshclModel qyshcl2 : list) {
				switch (qyshcl2.getCllx()) {
				case 1:
					mv.addObject("yyzz", qyshcl2.getShcl());
					break;
				case 2:
					mv.addObject("zzjg", qyshcl2.getShcl());
					break;
				case 3:
					mv.addObject("swdj", qyshcl2.getShcl());
					break;
				case 4:
					mv.addObject("qyzz", qyshcl2.getShcl());
					break;
				case 5:
					mv.addObject("wtzm", qyshcl2.getShcl());
					break;
				case 6:
					mv.addObject("szhy", qyshcl2.getShcl());
					break;
				default:
					break;
				}
			}
		}
		else {
			mv.addObject("isnew", "1");
		}
		
		return mv;
	}
	
	/**
	 * Description ：会员账号管理
	 */
	@RequestMapping("member/memberzhgl")
	public String memberzhgl() {
		
		return "/front/frontgoods/member/hyzhgl";
	}
	
	/**
	 * Description ：会员信息新增和编辑
	 * @throws Exception 
	 */
	@RequestMapping(value ="/member/memberxxglnewandedit", method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> memberxxglnewandedit(@ModelAttribute YhxxModel yhxx)throws Exception {
	
		Map<String,Object> map = new HashMap<String,Object>();
		
		String fileUrl = request.getParameter("logofilename").toString();
		String yyzzfilename = request.getParameter("yyzzfilename");
		String zzjgfilename = request.getParameter("zzjgfilename");
		String swdjfilename = request.getParameter("swdjfilename");
		String qyzzfilename = request.getParameter("qyzzfilename");
		String wtzmfilename = request.getParameter("wtzmfilename");
		String szhyfilename = request.getParameter("szhyfilename");
		String qyjjfilename = request.getParameter("qyjjfilename");
		String isnew = request.getParameter("isnew").toString();
		
		String yhid = "";
		if (request.getSession().getAttribute("yhid")!=null) {
			yhid = request.getSession().getAttribute("yhid").toString();
		}
		yhxx.setYhid(yhid);
		yhxx.setQytx(fileUrl);
		yhxx.setJjtp(qyjjfilename);
		if (isnew.equals("1")) {
			//新增
			iyhxxService.insertSelective(yhxx,yyzzfilename,zzjgfilename,swdjfilename,qyzzfilename,wtzmfilename,szhyfilename);
		}
		else {
			//修改
			iyhxxService.updateSelective(yhxx,yyzzfilename,zzjgfilename,swdjfilename,qyzzfilename,wtzmfilename,szhyfilename);
			YhxxModel yhxxmodel = (YhxxModel)request.getSession().getAttribute("yhxxModel");
			yhxxmodel.setYhzt(0);
			session.setAttribute("yhxxModel", yhxxmodel);
		}
		
		map.put("message", 1);
		return map;
	}
	
	private String uploadDoc(MultipartFile articleFile)
			throws Exception {
		
		String baseFolder = this.getClass().getClassLoader()
				.getResource("../../upload/images").getPath();
		File folder = new File(baseFolder);
		
		String newFileName = UUID.randomUUID() + articleFile.getOriginalFilename().substring(articleFile.getOriginalFilename().lastIndexOf("."));
		
		FileUtils.copyInputStreamToFile(articleFile.getInputStream(),
				new File(folder,newFileName));
		return mainDomain + "/upload/images/" +  newFileName;
	}
	
	@RequestMapping(value = "member/fileUpload", method = { RequestMethod.POST, RequestMethod.GET })   
    public  void fileUpload(@RequestParam(value = "file") MultipartFile file,
    		HttpServletRequest request) throws Exception {    
            //这里要注意 @RequestParam(value = "file")必须和jsp中的文件上传框的id保持一致，  
            //你jsp中id=“filefile”这里就要用@RequestParam(value = "filefile")  
		
		String name = uploadDoc(file);
		response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("{\"message\":\"Y\"}");
        response.getWriter().write("{\"fileName\":" + name + "}");
    }
	
	/**
	 * Description ：会员密码修改
	 */
	@RequestMapping(value ="/member/passwordedit", method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> passwordedit(HttpServletRequest request)throws Exception {
	
		Map<String,Object> map = new HashMap<String,Object>();
		
		String oldpwd = request.getParameter("oldpwd").toString();
		String newpwd = request.getParameter("newpwd").toString();
		String yhid = "";
		
		if (request.getSession().getAttribute("yhid")!=null) {
			yhid = request.getSession().getAttribute("yhid").toString();
		}
		DlxxModel dlxxOld = idlxxService.getOne(new DlxxDTO(yhid));
		
		if (dlxxOld!=null) {
			//用户存在可以修改
			if (dlxxOld.getMm().equals(CipherUtils.MD5Encode(oldpwd))) {
				//相同，修改
				dlxxOld.setMm(CipherUtils.MD5Encode(newpwd));
				idlxxService.updateByPrimaryKey(dlxxOld);
			}
		} 
		
		map.put("message", 1);
		return map;
	}
	
	@RequestMapping(value = "api/member/yyzzfileUpload", method = { RequestMethod.POST, RequestMethod.GET })   
    public void yyzzfileUpload(@RequestParam(value = "yyzzfile") MultipartFile file,   HttpServletRequest request) throws Exception {    
            //这里要注意 @RequestParam(value = "file")必须和jsp中的文件上传框的id保持一致，  
            //你jsp中id=“filefile”这里就要用@RequestParam(value = "filefile")  
//		long file_size = 1024 * 1024 * 2;
//		String msg = "";
//        if (file.isEmpty()) {  
//        	msg = "文件不能为空"; 
//        	response.getWriter().write("{\"message\":"+ msg +"}");
//        	return;
//        }  
//        if (!Pattern.compile("^.*?\\.(jpg|png|gif|bmp|jpeg)$")
//				.matcher(file.getOriginalFilename().toLowerCase()).matches()) {   
//            msg = "选择正确的文件格式";
//            response.getWriter().write("{\"message\":"+ msg +"}");
//        	return;
//        }  
//        if (file.getSize()>file_size) {  
//           msg = "文件大小不能超过2M";
//           response.getWriter().write("{\"message\":"+ msg +"}");
//       	   return;
//        }
		
		String name = uploadDoc(file);
		response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("{\"message\":\"Y\"}");
        response.getWriter().write("{\"fileName\":" + name + "}");
    }
	
	@RequestMapping(value = "api/member/zzjgfileUpload", method = { RequestMethod.POST, RequestMethod.GET })   
    public void zzjgfileUpload(@RequestParam(value = "zzjgfile") MultipartFile file,   HttpServletRequest request) throws Exception {    
            //这里要注意 @RequestParam(value = "file")必须和jsp中的文件上传框的id保持一致，  
            //你jsp中id=“filefile”这里就要用@RequestParam(value = "filefile")  
				
		String name = uploadDoc(file);
		response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("{\"message\":\"Y\"}");
        response.getWriter().write("{\"fileName\":" + name + "}");
    }
	
	@RequestMapping(value = "api/member/swdjfileUpload", method = { RequestMethod.POST, RequestMethod.GET })   
    public void swdjfileUpload(@RequestParam(value = "swdjfile") MultipartFile file,   HttpServletRequest request) throws Exception {    
            //这里要注意 @RequestParam(value = "file")必须和jsp中的文件上传框的id保持一致，  
            //你jsp中id=“filefile”这里就要用@RequestParam(value = "filefile")  
				
		String name = uploadDoc(file);
		response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("{\"message\":\"Y\"}");
        response.getWriter().write("{\"fileName\":" + name + "}");  
    }
	
	@RequestMapping(value = "api/member/wtzmfileUpload", method = { RequestMethod.POST, RequestMethod.GET })   
    public void wtzmfileUpload(@RequestParam(value = "wtzmfile") MultipartFile file,   HttpServletRequest request) throws Exception {    
            //这里要注意 @RequestParam(value = "file")必须和jsp中的文件上传框的id保持一致，  
            //你jsp中id=“filefile”这里就要用@RequestParam(value = "filefile")  
				
		String name = uploadDoc(file);
		response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("{\"message\":\"Y\"}");
        response.getWriter().write("{\"fileName\":" + name + "}"); 
    }
	
	@RequestMapping(value = "api/member/qyzzfileUpload", method = { RequestMethod.POST, RequestMethod.GET })   
    public void qyzzfileUpload(@RequestParam(value = "qyzzfile") MultipartFile file,   HttpServletRequest request) throws Exception {    
            //这里要注意 @RequestParam(value = "file")必须和jsp中的文件上传框的id保持一致，  
            //你jsp中id=“filefile”这里就要用@RequestParam(value = "filefile")  
				
		String name = uploadDoc(file);
		response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("{\"message\":\"Y\"}");
        response.getWriter().write("{\"fileName\":" + name + "}");  
    }
	
	@RequestMapping(value = "api/member/szhyfileUpload", method = { RequestMethod.POST, RequestMethod.GET })   
    public void szhyfileUpload(@RequestParam(value = "szhyfile") MultipartFile file,   HttpServletRequest request) throws Exception {    
            //这里要注意 @RequestParam(value = "file")必须和jsp中的文件上传框的id保持一致，  
            //你jsp中id=“filefile”这里就要用@RequestParam(value = "filefile")  
				
		String name = uploadDoc(file);
		response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("{\"message\":\"Y\"}");
        response.getWriter().write("{\"fileName\":" + name + "}");
    }
	
	@RequestMapping(value = "api/member/jjtpfileUpload", method = { RequestMethod.POST, RequestMethod.GET })   
    public void jjtpfileUpload(@RequestParam(value = "jjtpfile") MultipartFile file,   HttpServletRequest request) throws Exception {    
            //这里要注意 @RequestParam(value = "file")必须和jsp中的文件上传框的id保持一致，  
            //你jsp中id=“filefile”这里就要用@RequestParam(value = "filefile")  
				
		String name = uploadDoc(file);
		response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("{\"message\":\"Y\"}");
        response.getWriter().write("{\"fileName\":" + name + "}");
    }
	
	/**
	 * Description ：会员交易账户管理
	 * @throws Exception 
	 */
	@RequestMapping("member/memberjyzhgl")
	public ModelAndView memberjyzhgl() throws Exception {
		
		ModelAndView mv = new ModelAndView("/front/frontgoods/member/hyjyzh");
		QyzhDTO qyzhDTO = new QyzhDTO();
		YhxxModel yhxxModel = (YhxxModel)request.getSession().getAttribute("yhxxModel");
		qyzhDTO.setYhid(yhxxModel.getYhid());
		QyzhModel qyzh = iqyzhService.getOne(qyzhDTO);
		if (qyzh!=null) {
			mv.addObject("isnew", "2");
			mv.addObject("qyzh", qyzh);
		}
		else {
			mv.addObject("isnew", "1");
		}
		
		return mv;
	}
	
	/**
	 * Description ：会员交易账号新增和编辑
	 * @throws Exception 
	 */
	@RequestMapping(value ="/member/memberjyzhglnewandedit", method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> memberjyzhglnewandedit(HttpServletRequest request,QyzhModel qyzh)throws Exception {
	
		Map<String,Object> map = new HashMap<String,Object>();
		
		YhxxModel yhxxModel = (YhxxModel)request.getSession().getAttribute("yhxxModel");
		qyzh.setYhid(yhxxModel.getYhid());
		String isnew = request.getParameter("isnew").toString();

		if (isnew.equals("1")) {
			//新增
			iqyzhService.insert(qyzh);
		}
		else {
			//修改
			iqyzhService.updateByPrimaryKey(qyzh);
		}
		
		map.put("message", 1);
		return map;
	}
}
